<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, nextTick, watch, reactive } from 'vue'
import { ElTree, ElInput, ElTag, ElMessage } from 'element-plus'
import { flatData } from '@/hooks/PublicFun'
import { useTable } from '@/hooks/web/useTable'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import GetSystemUserApi from '@/api/department/UserApi'
import DeptApi from '@/api/dept'
import { UserListAlltype } from '@/api/department/types'
import { DateFormat } from '@/hooks/PublicFun'
import { usePatrolGroupStore } from '@/store/modules/PlanGroupStore'
const { t } = useI18n()
const currentNodeKey = ref()
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await GetSystemUserApi.GetUser({
      deptId: unref(currentNodeKey),
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.rows || [],
      total: res.total || 0
    }
  },
  fetchDelApi: async () => {
    const res = await GetSystemUserApi.DeletUser(unref(ids)[0])
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const departmentList = ref<UserListAlltype[]>([])
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: '序号',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'index'
    }
  },
  {
    field: 'userName',
    label: '用户名',
    search: {
      component: 'Input',
      componentProps: {
        placeholder: '用户名'
      }
    },
    form: {
      component: 'Input',
      colProps: {
        span: 13
      }
    }
  },
  {
    field: 'password',
    label: '用户密码',
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    hidden: true,
    form: {
      component: 'InputPassword',
      hidden: true,
      componentProps: {
        strength: true
      },
      colProps: {
        span: 13
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'nickName',
    label: '昵称',
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 13
      }
    }
  },
  {
    field: 'loginDate',
    label: '登录时间',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      slots: {
        default: (data: any) => {
          return <>{DateFormat(data.loginDate)}</>
        }
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'loginIp',
    label: '登录IP',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'status',
    label: '状态',
    width: 100,
    search: {
      component: 'Select',
      componentProps: {
        placeholder: '状态',
        options: [
          {
            value: '0',
            label: '正常'
          },
          {
            value: '1',
            label: '停用'
          }
        ]
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          const status = data.row.status
          return (
            <>
              <ElTag type={status == '0' ? 'success' : 'danger'}>
                {status == '0' ? '正常' : '停用'}
              </ElTag>
            </>
          )
        }
      }
    },
    form: {
      component: 'Select',
      componentProps: {
        options: [
          {
            value: '0',
            label: '正常'
          },
          {
            value: '1',
            label: '停用'
          }
        ]
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElTag type={data.status == '0' ? 'success' : 'danger'}>
                {data.status == '0' ? '正常' : '停用'}
              </ElTag>
            </>
          )
        }
      }
    }
  },
  {
    field: 'sex',
    label: '性别',
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: [
          {
            value: '0',
            label: '男'
          },
          {
            value: '1',
            label: '女'
          }
        ]
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <span> {data.sex == '0' ? '男' : '女'}</span>
            </>
          )
        }
      }
    }
  },
  {
    field: 'deptId',
    label: '所属部门',
    detail: {
      slots: {
        default: (data: any) => {
          return flatData(departmentList.value).map((item) => {
            if (item.id == data.deptId) {
              return t(item.label)
            }
          })
        }
      }
    },
    search: {
      hidden: true
    },
    form: {
      component: 'TreeSelect',
      componentProps: {
        renderAfterExpand: false,
        showCheckbox: true,
        nodeKey: 'id',
        props: {
          label: 'label'
        },
        data: departmentList
      }
    },
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return flatData(departmentList.value).map((item) => {
        if (item.id == cellValue) {
          return t(item.label)
        }
      })
    }
  },
  {
    field: 'email',
    label: '邮箱',
    form: {
      component: 'Input'
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'phonenumber',
    label: '手机号',
    form: {
      component: 'Input'
    },
    search: {
      component: 'Input',
      componentProps: {
        placeholder: '手机号'
      }
    }
  },
  {
    field: 'createTime',
    label: '创建时间',
    width: 140,
    form: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: '操作',
    width: 200,
    fixed: 'right',
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data) => {
          if (data.row.admin == false) {
            return (
              <>
                <span class="TableBtn" onClick={() => action(data.row, 'detail')}>
                  查看
                </span>
                <span class="TableBtn" onClick={() => action(data.row, 'edit')}>
                  修改
                </span>
                <span class="TableBtn" onClick={() => ResetPwd(data.row)}>
                  重置密码
                </span>
                <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
                  删除
                </span>
              </>
            )
          }
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  currentPage.value = 1
  searchParams.value = params
  getList()
}
const treeEl = ref<typeof ElTree>()
const fetchDepartment = async () => {
  const res = await DeptApi.GetDeptListTree()
  departmentList.value = res.data
  currentNodeKey.value = (res.data[0] && res.data[0]?.children && res.data[0].children[0].id) || ''
  await nextTick()
  unref(treeEl)?.setCurrentKey(currentNodeKey.value)
}
fetchDepartment()

const currentDepartment = ref('')
watch(
  () => currentDepartment.value,
  (val) => {
    unref(treeEl)!.filter(val)
  }
)

const currentChange = (data: any) => {
  currentNodeKey.value = data.id
  currentPage.value = 1
  getList()
}

const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.departmentName.includes(value)
}

const dialogVisible = ref(false)

const dialogTitle = ref('')

const currentRow = ref<UserListAlltype>()
const actionType = ref('')

const AddAction = async () => {
  UserDetail.value = await GetSystemUserApi.GetUserInfo()
  dialogTitle.value = '新增'
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = 'add'
}

const delLoading = ref(false)
const ids = ref<number[]>([])

const delData = async (row?: UserListAlltype) => {
  currentNodeKey.value = null
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.userId]
    : elTableExpose?.getSelectionRows().map((v: UserListAlltype) => v.userId) || []
  delLoading.value = true

  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const UserDetail: any = ref({})
const action = async (row: UserListAlltype, type: string) => {
  UserDetail.value = await GetSystemUserApi.GetUserDetail(row.userId)
  UserDetail.value.data.roleIds = UserDetail.value.roleIds //角色
  UserDetail.value.data.postIds = UserDetail.value.postIds //岗位
  dialogTitle.value = t(type === 'edit' ? '修改' : '详情')
  dialogVisible.value = true
  actionType.value = type
  currentRow.value = {
    ...UserDetail.value.data,
    department: unref(treeEl)?.getCurrentNode() || {}
  }
}
const PswVisible = ref(false) //密码弹窗
const PswInput = ref<string>('')
const PswData: any = ref({})
const PswSaveLoading = ref(false)
const PswSave = async () => {
  const res = await GetSystemUserApi.ResetPwd({
    userId: PswData.value.userId,
    password: PswInput.value
  })
  if (res) {
    PswVisible.value = false
    ElMessage.success('重置成功')
  }
}
const GroupStore = usePatrolGroupStore()
const ResetPwd = async (rows: any) => {
  PswVisible.value = true
  PswData.value = rows
}
const writeRef = ref<ComponentRef<typeof Write>>()
const saveLoading = ref(false)
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res: any = ref(false)
    if (actionType.value == 'add') {
      res.value = await GetSystemUserApi.AddUser(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else {
      res.value = await GetSystemUserApi.EditUser(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    }
    if (res.value) {
      currentNodeKey.value = null
      dialogVisible.value = false
      currentPage.value = 1
      getList()
      GroupStore.setUserListAll() //其他页面获取执行用户列表
    }
  }
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px">
      <div class="flex justify-center items-center">
        <ElInput v-model="currentDepartment" placeholder="搜索部门" class="mb-[10px]" clearable />
      </div>
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        :expand-on-click-node="false"
        node-key="id"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'label'
        }"
        :filter-node-method="filterNode"
        @current-change="currentChange"
      >
        <template #default="{ data }">
          <div :title="data.label" class="whitespace-nowrap overflow-ellipsis overflow-hidden">
            {{ data.label }}
          </div>
        </template>
      </ElTree>
    </ContentWrap>
    <ContentWrap class="flex-[3] ml-20px">
      <BaseButton size="small" type="primary" @click="AddAction" class="AddbtnStyle">
        <Icon icon="ep:plus" :size="12" />添加
      </BaseButton>
      <Search
        :schema="allSchemas.searchSchema"
        @search="setSearchParams"
        @reset="setSearchParams"
      />
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>

    <Dialog v-model="dialogVisible" :title="dialogTitle">
      <Write
        v-if="actionType !== 'detail'"
        ref="writeRef"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
        :UserDetail="UserDetail"
      />

      <Detail
        v-if="actionType === 'detail'"
        :detail-schema="allSchemas.detailSchema"
        :current-row="currentRow"
        :UserDetail="UserDetail"
      />

      <template #footer>
        <BaseButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
    <Dialog v-model="PswVisible" title="重置密码" maxHeight="100px" style="width: 500px">
      <span class="PswSpan"> 请输入"{{ PswData.userName }}"的新密码</span>
      <el-input v-model="PswInput" style="width: 100%" show-password />
      <template #footer>
        <BaseButton type="primary" :loading="PswSaveLoading" @click="PswSave"> 确定 </BaseButton>
        <BaseButton @click="PswVisible = false">取消</BaseButton>
      </template>
    </Dialog>
  </div>
</template>
<style scoped>
:deep(.TableBtn) {
  margin: 0 3px;
  font-size: 12px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600 !important;
}
.AddbtnStyle {
  margin-bottom: 18px;
  margin-right: 10px;
}
.PswSpan {
  font-size: 16px;
  display: inline-block;
  margin: 10px 0;
}
</style>
